package cn.edu.njnu.opengmpback.collaboration.controller;

  import cn.edu.njnu.opengmpback.collaboration.dao.TaskDependency.TaskDependencyDao;
  import cn.edu.njnu.opengmpback.collaboration.entity.TaskDependencyGraph;
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.web.bind.annotation.*;

  import javax.servlet.http.HttpServletRequest;
  import java.util.Date;
  import java.util.List;
  import java.util.Map;

  @CrossOrigin(origins = "http://localhost:5173")
  @RestController
  @RequestMapping("/task-dependency")
  public class TaskDependencyController {

      @Autowired
      private TaskDependencyDao taskDependencyDao;

      /**
       * 保存/更新项目的依赖关系图
       */
      @RequestMapping(value = "/save", method = RequestMethod.POST)
      public Object saveDependencyGraph(@RequestBody Map<String, Object> requestData) {
          try {
              String projectId = (String) requestData.get("projectId");
              @SuppressWarnings("unchecked")
              Map<String, List<String>> dependencies = (Map<String, List<String>>) requestData.get("dependencies");
              String creatorId = (String) requestData.get("creatorId");

              // 查找是否已存在
              TaskDependencyGraph existingGraph = taskDependencyDao.findByProjectId(projectId);

              if (existingGraph != null) {
                  // 更新现有记录
                  existingGraph.setDependencies(dependencies);
                  existingGraph.setUpdatedTime(new Date());
                  TaskDependencyGraph saved = taskDependencyDao.save(existingGraph);
                  return saved;
              } else {
                  // 创建新记录
                  TaskDependencyGraph newGraph = new TaskDependencyGraph(projectId, dependencies, creatorId);
                  TaskDependencyGraph saved = taskDependencyDao.save(newGraph);
                  return saved;
              }

          } catch (Exception e) {
              e.printStackTrace();
              return "Fail";
          }
      }

      /**
       * 获取项目的依赖关系图
       */
      @RequestMapping(value = "/get/{projectId}", method = RequestMethod.GET)
      public Object getDependencyGraph(@PathVariable String projectId) {
          try {
              TaskDependencyGraph graph = taskDependencyDao.findByProjectId(projectId);
              return graph != null ? graph : "None";
          } catch (Exception e) {
              e.printStackTrace();
              return "Fail";
          }
      }

      /**
       * 删除项目的依赖关系图
       */
      @RequestMapping(value = "/delete/{projectId}", method = RequestMethod.DELETE)
      public Object deleteDependencyGraph(@PathVariable String projectId) {
          try {
              taskDependencyDao.deleteByProjectId(projectId);
              return "Success";
          } catch (Exception e) {
              e.printStackTrace();
              return "Fail";
          }
      }
  }